package com.coocaa.framework.bigdata;

import android.content.Context;
import android.os.Environment;
import android.os.RemoteException;
import android.provider.Settings;

import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedaemon.LiteDaemon;
import com.coocaa.x.service.litedownloader.aidl.IDownloaderServiceListener;
import com.coocaa.x.service.litedownloader.data.DownloadError;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;
import com.coocaa.x.service.litedownloader.data.ProcessInfo;
import com.coocaa.x.service.litepm.aidl.ILitePMInstallListener;
import com.coocaa.x.service.litepm.aidl.ILitePMUninstallListener;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.coocaa.x.service.litepm.data.InstallParams;
import com.skyworth.framework.skysdk.util.SdCardChecker;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;

public class BigDataLog extends LiteDaemon {
    private static LiteDaemonInfo info = null;

    static {
        info = new LiteDaemonInfo();
        info.id = "com.coocaa.framework.bigdata.BigDataLog";
        info.name = "BigDataLog";
    }

    public static void log4InstallSuccess(String pkgName, String appName, String version) {
        String log = "[%s(%s@%s)]INSTALL_SUCCESS";
        LogAPIForAppStore.appStatusNew(-1, pkgName, appName, "安装成功",
                String.format(log, appName, pkgName, version));
    }

    public static void log4InstallFailed(String pkgName, String appName, String version,
                                         String error_msg) {
        String log = "[%s(%s@%s)]INSTALL_FAILED:%s";
        LogAPIForAppStore.reportError(String.format(log, appName, pkgName, version, error_msg));
    }

    public static void log4DownloadError(String url, String appName, String pkgName,
                                         String error_msg) {
        String log = "[%s(%s):%s]DOWNLOAD_ERROR:%s";
        LogAPIForAppStore.reportError(String.format(log, appName, pkgName, url, error_msg));
    }

    public static void log4DownloadSuccess(String appName, String pkgName) {
        String log = "[%s(%s)]DOWNLOAD_SUCCESS";
        LogAPIForAppStore.appStatusNew(-1, pkgName, appName, "下载成功",
                String.format(log, appName, pkgName));
    }

    @Override
    protected void onDestroy() {
        try {
            XServiceManager.getDownloaderService().clearListener(downloaderStub);
            XServiceManager.getLitePMService().removeInstallListener(installStub);
            XServiceManager.getLitePMService().removeUninstallListener(uninstallStub);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public BigDataLog() {
        super(info);
    }

    @Override
    protected void onCreate(Context context) {
        try {
            XServiceManager.getDownloaderService().setListener(downloaderStub);
            XServiceManager.getLitePMService().addInstallListener(installStub);
            XServiceManager.getLitePMService().addUninstallListener(uninstallStub);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

    private ILitePMInstallListener.Stub installStub = new ILitePMInstallListener.Stub() {
        @Override
        public void onInstallStart(String apkfile, AppInfo info, final InstallParams params) throws RemoteException {
            AppDataLog log = new AppDataLog();
            log.setData(info.appName,info.pkgName,info.versionCode);
            submitInstallStartLog(log.toJSONString());
        }

        @Override
        public void onInstallEnd(String apkfile, final AppInfo info, final int result, final String extra, final InstallParams params) throws RemoteException {
            post(new Runnable() {
                @Override
                public void run() {
                    AppDataLog log = new AppDataLog();
                    log.setData(info.appName,info.pkgName,info.versionCode);
                    submitInstallEndLog(result,log.toJSONString(),extra);
                    if (params != null && params.getFrom() == InstallParams.INSTALL_FROM.COOCAA_MARKET) {
                        if (result == 0) {
                            log4InstallSuccess(info.pkgName, info.appName, info.versionName);
                        } else {
                            log4InstallFailed(info.pkgName, info.appName, info.versionName, extra);
                        }
                    }
                    if (params != null && (params.getFrom() == InstallParams.INSTALL_FROM.COOCAA_MARKET
                            ||params.getFrom() == InstallParams.INSTALL_FROM.COOCAA_PUSH)) {
                        if (result == 0) {
                            try {
                                XServiceManager.getLiteCCConnectorService().installAppPoints(info.pkgName);
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            });
        }
    };

    private ILitePMUninstallListener.Stub uninstallStub = new ILitePMUninstallListener.Stub() {
        @Override
        public void onUninstallStart(AppInfo info) throws RemoteException {
            AppDataLog log = new AppDataLog();
            log.setData(info.appName, info.pkgName, info.versionCode);
            submitUninstallStartLog(log.toJSONString());
        }

        @Override
        public void onUninstallEnd(AppInfo info, int result, String extra) throws RemoteException {
            AppDataLog log = new AppDataLog();
            log.setData(info.appName, info.pkgName, info.versionCode);
            submitUninstallEndLog(result, log.toJSONString(), extra);
        }
    };

    private void submitLog(DownloadTask task, String id, boolean isError, DownloadError errMsg) {
        if(task == null)
            return;

        LogUtils.i("submitLog", "id: " + id + ", task.filename: " + task.filename);
        LogUtils.SubmitLog submitLog = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, id);
        submitLog.addParam("task_name", task.filename);
        submitLog.addParam("task_url", task.url);
        submitLog.addParam("task_savepath", task.savepath);

        if (isError && errMsg != null) {
            submitLog.addParam("error", errMsg.error);
            LogUtils.i("downloader", "errMag: " + errMsg.error);
        }

        LogUtils.submit(submitLog);

    }

    private IDownloaderServiceListener.Stub downloaderStub = new IDownloaderServiceListener.Stub() {
        @Override
        public void onReady(DownloadTask task) throws RemoteException {

        }

        @Override
        public void onPrepare(DownloadTask task) throws RemoteException {

        }

        @Override
        public void onStart(final DownloadTask task) throws RemoteException {
            post(new Runnable() {
                @Override
                public void run() {
                    submitLog(task, "download_onstart", false, null);
                }
            });

        }

        @Override
        public void onStop(DownloadTask task) throws RemoteException {

        }

        @Override
        public void onFinish(final DownloadTask task) throws RemoteException {

            post(new Runnable() {
                @Override
                public void run() {
                    submitLog(task, "download_onsuccess", false, null);
                    if (task != null && task.extra != null && !task.extra.equals("")) {
                        DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
                        log4DownloadSuccess(extra.title, extra.pkgname);
                    }
                }
            });

        }

        @Override
        public void onDelete(DownloadTask task) throws RemoteException {

        }

        @Override
        public void onProcessInfo(DownloadTask task, ProcessInfo info) throws RemoteException {

        }

        @Override
        public void onError(final DownloadTask task, final DownloadError error) throws RemoteException {


            post(new Runnable() {
                @Override
                public void run() {

                    submitLog(task, "download_onfailed", true, error);
                    if (task != null && task.extra != null && !task.extra.equals("")) {
                        DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
                        log4DownloadError(task.url, extra.title, extra.pkgname, error.error);
                    }
                }
            });

        }
    };

    private void submitInstallStartLog(String appInfo){
        LogUtils.SubmitLog log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, "install_app_onstart");
        log.addParam("app", appInfo);
        int ret = Settings.Secure.getInt(mContext.getContentResolver(), "default_install_location", 0);
        LogUtils.d("log", "submitInstallStartLog  appinfo:" + appInfo + " ret:" + ret);
        switch (ret) {
            case 0:
            case 1:
                log.addParam("location", "internal");
                break;
            case 2:
                log.addParam("location", " externel");
                break;
        }
        if (SdCardChecker.isSDCardAvaiable()) // 只有sdcard存在的情况下才有这么个功能
        {
            boolean isSDEmulated = Environment.isExternalStorageEmulated();
            LogUtils.d("log", "getManagerData------isSDEmulated:" + isSDEmulated);
            if (!isSDEmulated)
                log.addParam("sdcard", "externel");
            else
                log.addParam("sdcard", "virtual");
        } else {
            log.addParam("sdcard", "none");
        }
        LogUtils.submit(log);
    }

    private void submitInstallEndLog(int result,String appInfo,String extra) {
        LogUtils.SubmitLog log = null;
        if (result == 0)
            log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, "install_app_onsuccess");
        else {
            log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, "install_app_onfailed");
            log.addParam("error",extra);
        }
        log.addParam("app", appInfo);
        int ret = Settings.Secure.getInt(mContext.getContentResolver(), "default_install_location", 0);
        LogUtils.d("log","submitInstallEndLog  appinfo:"+appInfo+" ret:"+ret);
        switch (ret) {
            case 0:
            case 1:
                log.addParam("location", "internal");
                break;
            case 2:
                log.addParam("location", " externel");
                break;
        }
        if (SdCardChecker.isSDCardAvaiable()) // 只有sdcard存在的情况下才有这么个功能
        {
            boolean isSDEmulated = Environment.isExternalStorageEmulated();
            LogUtils.d("test", "getManagerData------isSDEmulated:" + isSDEmulated);
            if (!isSDEmulated)
                log.addParam("sdcard", "externel");
            else
                log.addParam("sdcard", "virtual");
        } else {
            log.addParam("sdcard", "none");
        }
        LogUtils.submit(log);
    }

    private void submitUninstallStartLog(String info){
        LogUtils.SubmitLog log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, "uninstall_app_onstart");
        log.addParam("app", info);
        LogUtils.submit(log);
    }

    private void submitUninstallEndLog(int result, String info, String extra){
        LogUtils.SubmitLog log = null;
        if (result == 0)
            log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, "uninstall_app_onsuccess");
        else {
            log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, "uninstall_app_onfailed");
            log.addParam("error",extra);
        }
        log.addParam("app", info);
        LogUtils.submit(log);
    }
}
